import React from 'react';
import { connect } from 'dva';
import router from 'umi/router';
import queryString from 'query-string';
import { PlusOutlined, ExclamationCircleOutlined } from '@ant-design/icons';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Card, Divider, message, Button, Spin, Modal, InputNumber } from 'antd';

import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import DescriptionList from '@/components/DescriptionList';
import FooterToolbar from '@/components/FooterToolbar';
import StandardTable from '@/components/StandardTable';
import Authorized from '@/utils/Authorized';
import { checkPermissions } from '@/utils/authority';
import styles from '@/utils/utils.less';
import Area from '../../components/Area';
import DictCode from '../../components/DictCode';

const { Description } = DescriptionList;
const FormItem = Form.Item;
const { confirm } = Modal;

@connect(({ speicf, loading, publicdata }) => ({
  loading: loading.effects['speicf/getDetail'] || loading.effects['speicf/fetchList'],
  modalLoading: loading.effects['speicf/getSpeDetail'],
  submitLoading: loading.effects['speicf/submit'],
  dictCode: publicdata.dictCode,
  detailInfo: speicf.detailInfo,
  pageData: speicf.pageData,
  speicfInfo: speicf.speicfInfo,
  attrVoList: speicf.attrVoList,
}))
class BasicForm extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      pdId: null,
      isDetail: false,
      columns: [
        {
          title: '地区',
          dataIndex: 'areaIds',
          onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        },
        {
          title: '建议售价',
          dataIndex: 'suggPrice',
          align: 'right',
          onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
          render: val => (val || val === 0 ? val : '--'),
        },
        {
          title: '操作',
          dataIndex: 'operation',
          align: 'center',
          onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
          render: (text, record) => (
            <span>
              {checkPermissions('mgr:baseProductQuery:inertSpeicfPrice') && (
                <a
                  onClick={() => {
                    this.update(record);
                  }}
                >
                  修改
                </a>
              )}
              {checkPermissions('mgr:baseProductQuery:inertSpeicfPrice') &&
                checkPermissions('mgr:baseProduct:deletePrice') && <Divider type="vertical" />}
              {checkPermissions('mgr:baseProduct:deletePrice') && (
                <a onClick={() => this.delList(record)}>删除</a>
              )}
            </span>
          ),
        },
      ],
      selectedRows: [],
      selectedRowKeys: [],
      modalVisible: false,
      specifId: null,
    };
  }

  componentDidMount() {
    const { location, dispatch } = this.props;
    const { columns } = this.state;
    const { pdId, isDetail = 'false' } = queryString.parse(location.search);
    // 获取字典
    dispatch({
      type: 'publicdata/fetchDictCode',
      payload: [
        'PAY_FEES_WAY',
        'BIZ_INS_TYPE',
        'ISNULL_FLAG',
        'PRODUCT_WAGE_TYPE',
        'PD_CATE',
        'PD_BILL_FREQ',
      ],
    });
    // 获取详情数据
    dispatch({
      type: 'speicf/getDetail',
      payload: {
        pdId,
      },
    }).then(data => {
      let newColumns = columns;
      const attrColums = [];
      if (isDetail === 'true') {
        newColumns = columns.filter((item, index, arr) => index !== arr.length - 1);
      }
      if (data.attrVoList && data.attrVoList.length) {
        data.attrVoList.forEach(item => {
          attrColums.push({
            title: item.stdName,
            dataIndex: item.stdInfo,
            onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
          });
        });
      }
      this.setState({ columns: [...attrColums, ...newColumns] });
    });
    this.setState({ pdId, isDetail }, () => {
      this.getList();
    });
  }

  // 获取列表数据
  getList = (currentPage = 1, pageSize = 10) => {
    const { dispatch } = this.props;
    const { pdId } = this.state;
    const pageArg = { currentPage, pageSizes: pageSize };
    const values = {
      pdId,
      pageArg,
    };
    dispatch({
      type: 'speicf/fetchList',
      payload: {
        ...values,
      },
    });
  };

  // 点击复选框
  handleSelectRows = (selectedRows, selectedRowKeys) => {
    this.setState({ selectedRows, selectedRowKeys });
  };

  // 表格有变化：比如：切换页码
  handleStandardTableChange = pagination => {
    this.getList(pagination.current, pagination.pageSize);
  };

  // 切换模态框：新增、修改
  handleModalVisible = flag => {
    this.setState({ modalVisible: !!flag });
  };

  // 新增规则
  add = () => {
    const { dispatch, form, attrVoList } = this.props;
    form.resetFields();
    attrVoList.forEach((_, index) => {
      attrVoList[index].attrValList = [];
    });
    dispatch({
      type: 'speicf/updateModelData',
      payload: { speicfInfo: {}, attrVoList },
    });
    this.setState({ specifId: null }, () => {
      this.handleModalVisible(true);
    });
  };

  // 修改规则
  update = record => {
    const { dispatch } = this.props;
    const { priceId, pdId, specifId, areaId } = record;
    dispatch({
      type: 'speicf/getSpeDetail',
      payload: { pdId, specifId, areaCode: areaId },
    });
    this.setState({ selectedRowKeys: priceId, selectedRows: record, specifId }, () => {
      this.handleModalVisible(true);
    });
  };

  // 提交数据
  submit = () => {
    const { dispatch, form } = this.props;
    const { pdId, specifId } = this.state;
    form.validateFields((err, values) => {
      if (!err) {
        dispatch({
          type: 'speicf/submit',
          payload: { values, pdId, specifId },
        }).then(response => {
          if (response.success) {
            this.setState({ specifId: null }, () => {
              this.handleModalVisible(false);
              this.getList();
              message.success(specifId ? '保存成功!' : '新增成功！');
            });
          } else {
            message.warning(`${response.data || '保存失败！'}`);
          }
        });
      }
    });
  };

  // 删除
  delList = record => {
    const {
      dispatch,
      pageData: {
        pagination: { current, pageSize, total },
      },
    } = this.props;
    const { priceId, specifId, areaId, suggPrice } = record;
    this.setState({ selectedRowKeys: priceId, selectedRows: record });
    confirm({
      title: '你确定要删除此条产品定价规则信息吗？',
      icon: <ExclamationCircleOutlined />,
      okText: '确定',
      okType: 'primary',
      cancelText: '取消',
      style: { top: 200 },
      onOk: () => {
        dispatch({
          type: 'speicf/deleteList',
          payload: { specifId, areaId: areaId.split(','), suggPrice },
        }).then(res => {
          if (res.success) {
            const selectedLen = 1;
            if (current > 1 && (total % pageSize === selectedLen || pageSize === selectedLen)) {
              this.getList(current - 1, pageSize);
            } else {
              this.getList(current, pageSize);
            }
            this.setState({ selectedRowKeys: [], selectedRows: [] });
            message.success('删除成功！');
          } else {
            message.warning(`${res.message || '删除失败'}`);
          }
        });
      },
      onCancel: () => {
        this.setState({ selectedRowKeys: [], selectedRows: [] });
      },
    });
    return true;
  };

  render() {
    const {
      loading,
      form,
      detailInfo,
      pageData,
      speicfInfo,
      attrVoList,
      modalLoading,
      submitLoading,
    } = this.props;
    const { getFieldDecorator } = form;
    const { isDetail, columns, selectedRowKeys, selectedRows, modalVisible, specifId } = this.state;
    // 模态框布局
    const formItemLayoutModal = {
      labelCol: { md: { span: 6 } },
      wrapperCol: { md: { span: 16, offset: 1 } },
    };
    // 模态框配置
    const modalConfig = {
      width: 560,
      title: `${(specifId && '修改') || '添加'}售价规则`,
      visible: modalVisible,
      destroyOnClose: true,
      confirmLoading: submitLoading,
      onOk: this.submit,
      onCancel: () => {
        this.setState({ selectedRowKeys: [], selectedRows: [], specifId: null });
        this.handleModalVisible(false);
      },
    };

    return (
      <PageHeaderWrapper>
        <Spin tip="loading..." spinning={loading}>
          <Card
            title={<span style={{ fontWeight: 'bolder' }}>产品定价</span>}
            style={{ marginBottom: 24 }}
            bordered={false}
          >
            <DescriptionList style={{ marginBottom: 24 }}>
              <Description term="产品名称">{detailInfo.pdName || '--'}</Description>
              <Description term="默认建议售价">
                {detailInfo.suggPrice || detailInfo.suggPrice === 0 ? detailInfo.suggPrice : '--'}
              </Description>
              <Description term="产品编号">{detailInfo.pdCode || '--'}</Description>
              <Description term="默认建议售价">{detailInfo.pdCateName || '--'}</Description>
              <Description term="产品编号">{detailInfo.billFreqName || '--'}</Description>
            </DescriptionList>
            <p style={{ lineHeight: '20px', color: 'rgba(0, 0, 0, 0.85)' }}>
              描述：
              <span style={{ color: ' rgba(0, 0, 0, 0.65)' }}>{detailInfo.pdInfo || '--'}</span>
            </p>
            <Divider />
            <Card
              title={<span style={{ fontWeight: 'bolder' }}>特殊售价规则</span>}
              style={{ marginBottom: 24 }}
              bordered={false}
            >
              {isDetail === 'false' && (
                <Authorized authority="mgr:baseProductQuery:inertSpeicfPrice" noMatch={null}>
                  <Button type="primary" style={{ marginBottom: 16 }} onClick={() => this.add()}>
                    <PlusOutlined />
                    新增
                  </Button>
                </Authorized>
              )}
              <StandardTable
                selectedRows={selectedRows}
                selectedRowKeys={selectedRowKeys}
                data={pageData}
                rowKey="priceId"
                columns={columns}
                onSelectRow={this.handleSelectRows}
                onChange={this.handleStandardTableChange}
                rowSelection={
                  isDetail === 'true' ? null : { selectedRowKeys, onChange: this.handleSelectRows }
                }
              />
            </Card>
          </Card>
          <Modal {...modalConfig}>
            <Spin tip="loading..." spinning={modalLoading || false}>
              <Form layout="horizontal">
                {attrVoList.map(attr => (
                  <FormItem
                    {...formItemLayoutModal}
                    key={attr.attrId}
                    label={attr.stdName}
                    className={styles.productPrice}
                  >
                    {getFieldDecorator(attr.attrId, {
                      rules: [{ required: true, message: '请选择' }],
                      initialValue: attr.attrValList,
                    })(
                      <DictCode
                        // eslint-disable-next-line no-nested-ternary
                        inputType={attr.inputType === 5 ? '2' : attr.inputType === 4 ? '1' : '3'}
                        style={{ width: '100%' }}
                        dictType={attr.dictType}
                      />
                    )}
                  </FormItem>
                ))}
                <FormItem {...formItemLayoutModal} label="地区">
                  {getFieldDecorator('areaIds', {
                    rules: [{ required: true, message: '请选择' }],
                    initialValue: speicfInfo.areaIds,
                  })(<Area mode="multiple" labelInValue />)}
                </FormItem>
                <FormItem {...formItemLayoutModal} label="建议售价">
                  {getFieldDecorator('suggPrice', {
                    rules: [{ required: true, message: '请输入' }],
                    initialValue: speicfInfo.suggPrice,
                  })(
                    <InputNumber
                      min={0}
                      max={99999}
                      placeholder="请输入"
                      style={{ width: '100%' }}
                      precision={2}
                    />
                  )}
                </FormItem>
              </Form>
            </Spin>
          </Modal>
          <FooterToolbar style={{ width: '100%' }}>
            <Button onClick={() => router.goBack()}>返回</Button>
          </FooterToolbar>
        </Spin>
      </PageHeaderWrapper>
    );
  }
}
const BasicFormList = Form.create()(BasicForm);
export default BasicFormList;
